program TAudioConverter;

uses
  madExcept,
  madLinkDisAsm,
  madListHardware,
  madListProcesses,
  madListModules,
  Forms,
  SysUtils,
  Messages,
  Windows,
  UnitMain in 'Forms\UnitMain.pas' {MainForm} ,
  UnitLog in 'Forms\UnitLog.pas' {LogForm} ,
  windows7taskbar in 'Units\windows7taskbar.pas',
  MediaInfoDLL in 'Units\MediaInfoDLL.pas',
  UnitInfo in 'Forms\UnitInfo.pas' {InfoForm} ,
  UnitAbout in 'Forms\UnitAbout.pas' {AboutForm} ,
  UnitUpdater in 'Forms\UnitUpdater.pas' {UpdaterForm} ,
  UnitSox in 'Forms\UnitSox.pas' {SoXForm} ,
  UnitProgress in 'Forms\UnitProgress.pas' {ProgressForm} ,
  UnitEncoder in 'Units\UnitEncoder.pas',
  JvCpuUsage in 'Units\JvCpuUsage.pas',
  UnitSettings in 'Forms\UnitSettings.pas' {SettingsForm} ,
  UnitFileInfo in 'Units\UnitFileInfo.pas';

{$R *.res}

{
  This procedure and WMCopyData and CreateParams procedures in UnitMain are
  copied from http://stackoverflow.com/questions/8688078/preventing-multiple-instances-but-also-handle-the-command-line-parameters.
  Thanks to David Heffernan.
}
procedure Main;
var
  i: Integer;
  Arg: string;
  Window: HWND;
  CopyDataStruct: TCopyDataStruct;
begin
  Window := FindWindow(SWindowClassName, nil);
  if Window = 0 then
  begin
    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    // ReportMemoryLeaksOnShutdown := True;
    Application.Title := 'TAudioConverter';
    Application.CreateForm(TMainForm, MainForm);
    Application.CreateForm(TLogForm, LogForm);
    Application.CreateForm(TInfoForm, InfoForm);
    Application.CreateForm(TAboutForm, AboutForm);
    Application.CreateForm(TUpdaterForm, UpdaterForm);
    Application.CreateForm(TSoXForm, SoXForm);
    Application.CreateForm(TProgressForm, ProgressForm);
    Application.CreateForm(TSettingsForm, SettingsForm);
    Application.Run;
  end
  else
  begin
    FillChar(CopyDataStruct, Sizeof(CopyDataStruct), 0);
    for i := 1 to ParamCount do
    begin
      Arg := ParamStr(i);
      CopyDataStruct.cbData := (Length(Arg) + 1) * Sizeof(Char);
      CopyDataStruct.lpData := PChar(Arg);
      SendMessage(Window, WM_COPYDATA, 0, NativeInt(@CopyDataStruct));
    end;
    SetForegroundWindow(Window);
  end;
end;

begin
  Main;

end.
